<template>
  <div id="assignPermissionPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 角色簡要信息面板 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="角色信息">
        <a-descriptions :column="2">
          <a-descriptions-item label="角色ID">{{
            roleDetail.id
          }}</a-descriptions-item>
          <a-descriptions-item label="角色名稱">{{
            roleDetail.name
          }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card title="分配權限" :loading="loading">
        <a-checkbox-group v-model:value="checkedKeys" style="width: 100%">
          <a-collapse v-model:activeKey="activeKey" style="width: 100%">
            <a-collapse-panel
              v-for="(module, index) in permissionList"
              :key="index.toString()"
              :header="module.module"
            >
              <!-- 添加調試信息 -->
              <div v-if="module.permissions.length === 0">該模塊暫無權限</div>
              <div v-else class="checkbox-container">
                <a-checkbox
                  v-for="permission in module.permissions"
                  :value="permission.name"
                  style="margin-right: 16px"
                >
                  {{ permission.title }}
                </a-checkbox>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </a-checkbox-group>
        <div class="button-container">
          <a-button type="primary" @click="handleSubmit">提交</a-button>
        </div>
      </a-card>
      <BackButton />
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { roleApi } from "@/api";
import { useRoute } from "vue-router";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import { usePermissionStore } from "@/store/permissionStore";

// 定義 Permission 和 PermissionModule 類型
interface Permission {
  name: string;
  title: string;
}

interface PermissionModule {
  module: string;
  permissions: Permission[];
}

const route = useRoute();
const roleDetail = ref({ id: 0, name: "" }); // 角色詳情數據
const activeKey = ref<string[]>([]);
const breadcrumbItems = [
  { url: "/role", name: "角色管理" },
  { url: "", name: "分配權限" },
];

const permissionStore = usePermissionStore();
const permissionList = ref<PermissionModule[]>([]);

const checkedKeys = ref<number[]>([]); // 存儲所有選中的權限 ID

const loading = ref(false);
onMounted(async () => {
  try {
    const roleId = Number(route.params.id);
    fetchRoleDetail(roleId);
    if (permissionStore.groupedPermissionList.length === 0) {
      await permissionStore.fetchGroupedPermissionList();
    }
    permissionList.value =
      permissionStore.groupedPermissionList as PermissionModule[];
    // 生成包含所有面板 key 的數組
    activeKey.value = permissionList.value.map((_, index) => index.toString());
    await fetchcheckedData(roleId);
  } finally {
    loading.value = false;
  }
});

const fetchRoleDetail = async (roleId: number) => {
  try {
    const { data } = await roleApi.getRoleDetail(roleId);
    roleDetail.value = data;
  } catch (error) {
    console.error("獲取角色詳情失敗", error);
  }
};

const fetchcheckedData = async (roleId: number) => {
  try {
    const { data } = await roleApi.getRolePermissions(roleId);
    checkedKeys.value = data;
  } catch (error) {
    console.error("獲取已分配權限失敗", error);
  }
};

// 處理提交表單的方法
const handleSubmit = async () => {
  const roleId = Number(route.params.id);
  const params = {
    permissions: checkedKeys.value, // 直接使用數組
  };
  try {
    await roleApi.assignRolePermission(roleId, params);
    message.success("分配權限成功");
  } catch (error) {
    console.error("分配權限失敗", error);
  }
};
</script>

<style scoped>
.button-container {
  text-align: right;
  margin-top: 16px;
}

.checkbox-container {
  display: flex;
  flex-wrap: wrap;
}
</style>
